package com.yu.provider;

import com.yu.loader.ExtensionLoader;
import com.yu.registrar.ServiceRegistrar;
import com.yu.service.RpcServiceProperties;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Currency;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @PackageName: com.yu.provider
 * @Description:
 * @Version: v1.0.0
 * @Author: yuweilin
 * @Date: 13:24
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ------------------------------------------------------------
 * 2021/1/23      yuweilin         v1.0.0               新建
 */
@Slf4j
public class ServiceProviderImpl implements ServiceProvider{
    /**
     * 这个是用来发布服务的zk注册器
     */
    private final ServiceRegistrar serviceRegistrar;
    /**
     * 用来存储service
     * key的话是服务的名字（接口名+版本号+分组）
     * value的话是服务对象
     */
    private final Map<String,Object> serviceMap;

    /**
     * 注册的服务名，防止重复
     */
    private final Set<String> registeredService;

    public ServiceProviderImpl() {
        serviceMap = new ConcurrentHashMap<>();
        registeredService = ConcurrentHashMap.newKeySet();
        serviceRegistrar = ExtensionLoader.getExtensionLoader(ServiceRegistrar.class).getExtension("zk");
    }

    @Override
    public void publishService(Object service, RpcServiceProperties rpcServiceProperties) {
        try {
            InetAddress localHost = InetAddress.getLocalHost().getLocalHost();
            Class<?> serviceRelatedInterface = service.getClass().getInterfaces()[0];
            String serviceName = serviceRelatedInterface.getCanonicalName();
            rpcServiceProperties.setServiceName(serviceName);
            addService(service,serviceRelatedInterface,rpcServiceProperties);
            serviceRegistrar.registerService(rpcServiceProperties.toRpcServiceName(),new InetSocketAddress(localHost, 9998));
        }catch (Exception e){
            e.printStackTrace();
            log.error("occur exception when getHostAddress");
        }
    }

    @Override
    public Object getService(RpcServiceProperties rpcServiceProperties) {
        Object service = serviceMap.get(rpcServiceProperties.toRpcServiceName());
        if (null==service){
            throw new RuntimeException("服务未发现");
        }
        return service;
    }

    @Override
    public void addService(Object service, Class<?> serviceClass, RpcServiceProperties rpcServiceProperties) {
        String rpcServiceName = rpcServiceProperties.toRpcServiceName();
        if (registeredService.contains(rpcServiceName)){
            return;
        }
        registeredService.add(rpcServiceName);
        serviceMap.put(rpcServiceName,service);
        log.info("增加服务:{} 和接口{}",rpcServiceName,serviceClass.getInterfaces());
    }

}
